document.addEventListener('DOMContentLoaded', function() {
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
    if (!currentUser) {
        alert('请先登录');
        window.location.href = '../login.html';
        return;
    }
    
    // 加载订单
    loadOrders('all');
    
    // 设置标签页点击事件
    document.querySelectorAll('.tab-btn').forEach(btn => {
        btn.addEventListener('click', function() {
            document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
            this.classList.add('active');
            const status = this.getAttribute('data-status');
            loadOrders(status);
        });
    });
});

function loadOrders(status) {
    const orders = JSON.parse(localStorage.getItem('orders')) || [];
    const currentUser = JSON.parse(localStorage.getItem('currentUser'));
    
    // 过滤当前用户的订单
    let filteredOrders = orders.filter(order => order.userId === currentUser.id);
    
    // 根据状态过滤
    if (status !== 'all') {
        filteredOrders = filteredOrders.filter(order => order.status === status);
    }
    
    const ordersList = document.getElementById('ordersList');
    ordersList.innerHTML = '';
    
    if (filteredOrders.length === 0) {
        ordersList.innerHTML = '<div class="empty-orders">暂无订单</div>';
        return;
    }
    
    // 按日期降序排序
    filteredOrders.sort((a, b) => new Date(b.date) - new Date(a.date));
    
    filteredOrders.forEach(order => {
        const orderCard = document.createElement('div');
        orderCard.className = 'order-card';
        
        let statusText = '';
        let statusClass = '';
        
        switch(order.status) {
            case 'pending':
                statusText = '待付款';
                statusClass = 'status-pending';
                break;
            case 'shipped':
                statusText = '待发货';
                statusClass = 'status-shipped';
                break;
            case 'delivered':
                statusText = '待收货';
                statusClass = 'status-delivered';
                break;
            case 'completed':
                statusText = '已完成';
                statusClass = 'status-completed';
                break;
            case 'canceled':
                statusText = '已取消';
                statusClass = 'status-canceled';
                break;
        }
        
        orderCard.innerHTML = `
            <div class="order-header">
                <span class="order-id">订单号：${order.id}</span>
                <span class="order-date">${order.date}</span>
                <span class="order-status ${statusClass}">${statusText}</span>
            </div>
            <div class="order-body" id="orderItems-${order.id}">
                <!-- 订单商品将通过JavaScript动态加载 -->
            </div>
            <div class="order-footer">
                <div class="order-total">总计：<span>¥${order.total.toFixed(2)}</span></div>
                <div class="order-actions" id="orderActions-${order.id}">
                    <!-- 订单操作按钮将通过JavaScript动态加载 -->
                </div>
            </div>
        `;
        
        ordersList.appendChild(orderCard);
        
        // 加载订单商品
        loadOrderItems(order);
        
        // 加载订单操作按钮
        loadOrderActions(order);
    });
}

function loadOrderItems(order) {
    const orderItemsContainer = document.getElementById(`orderItems-${order.id}`);
    if (!orderItemsContainer) return;
    
    order.items.forEach(item => {
        const orderItem = document.createElement('div');
        orderItem.className = 'order-item';
        orderItem.innerHTML = `
            <div class="order-item-img">
                <img src="${item.image}" alt="${item.name}">
            </div>
            <div class="order-item-info">
                <h4 class="order-item-name">${item.name}</h4>
                <div class="order-item-price">¥${item.price.toFixed(2)}</div>
                <div class="order-item-quantity">数量：${item.quantity}</div>
            </div>
        `;
        orderItemsContainer.appendChild(orderItem);
    });
}

function loadOrderActions(order) {
    const orderActionsContainer = document.getElementById(`orderActions-${order.id}`);
    if (!orderActionsContainer) return;
    
    let actionsHTML = '';
    
    switch(order.status) {
        case 'pending':
            actionsHTML = `
                <button class="btn-primary" onclick="payOrder('${order.id}')">立即支付</button>
                <button onclick="cancelOrder('${order.id}')">取消订单</button>
                <button onclick="viewOrderDetail('${order.id}')">订单详情</button>
            `;
            break;
        case 'shipped':
            actionsHTML = `
                <button onclick="viewOrderDetail('${order.id}')">订单详情</button>
                <button onclick="viewLogistics('${order.id}')">查看物流</button>
            `;
            break;
        case 'delivered':
            actionsHTML = `
                <button class="btn-primary" onclick="confirmReceipt('${order.id}')">确认收货</button>
                <button onclick="viewLogistics('${order.id}')">查看物流</button>
                <button onclick="viewOrderDetail('${order.id}')">订单详情</button>
            `;
            break;
        case 'completed':
            actionsHTML = `
                <button onclick="viewOrderDetail('${order.id}')">订单详情</button>
                <button onclick="applyAfterSale('${order.id}')">申请售后</button>
                <button onclick="deleteOrder('${order.id}')">删除订单</button>
            `;
            break;
        case 'canceled':
            actionsHTML = `
                <button onclick="viewOrderDetail('${order.id}')">订单详情</button>
                <button onclick="deleteOrder('${order.id}')">删除订单</button>
            `;
            break;
    }
    
    orderActionsContainer.innerHTML = actionsHTML;
}

// 订单操作函数
function payOrder(orderId) {
    alert(`模拟支付订单 ${orderId}`);
    // 实际项目中这里会跳转到支付页面
}

function cancelOrder(orderId) {
    if (confirm('确定要取消此订单吗？')) {
        const orders = JSON.parse(localStorage.getItem('orders')) || [];
        const orderIndex = orders.findIndex(o => o.id.toString() === orderId);
        
        if (orderIndex !== -1) {
            orders[orderIndex].status = 'canceled';
            localStorage.setItem('orders', JSON.stringify(orders));
            alert('订单已取消');
            window.location.reload();
        }
    }
}

function confirmReceipt(orderId) {
    if (confirm('确认收到商品了吗？')) {
        const orders = JSON.parse(localStorage.getItem('orders')) || [];
        const orderIndex = orders.findIndex(o => o.id.toString() === orderId);
        
        if (orderIndex !== -1) {
            orders[orderIndex].status = 'completed';
            localStorage.setItem('orders', JSON.stringify(orders));
            alert('订单已完成');
            window.location.reload();
        }
    }
}

function viewOrderDetail(orderId) {
    window.location.href = `order-detail.html?id=${orderId}`;
}

function viewLogistics(orderId) {
    alert(`查看订单 ${orderId} 的物流信息`);
}

function applyAfterSale(orderId) {
    alert(`为订单 ${orderId} 申请售后服务`);
}

function deleteOrder(orderId) {
    if (confirm('确定要删除此订单吗？删除后不可恢复')) {
        let orders = JSON.parse(localStorage.getItem('orders')) || [];
        orders = orders.filter(o => o.id.toString() !== orderId);
        localStorage.setItem('orders', JSON.stringify(orders));
        alert('订单已删除');
        window.location.reload();
    }
}